package org.thss.petri.gef.commands;

import org.eclipse.gef.commands.Command;
import org.thss.petri.model.Arc;
import org.thss.petri.model.Node;
import org.thss.petri.model.Place;
import org.thss.petri.model.Transition;

public class ReconnectArcCommand extends Command {
	private Arc connection;
	private Node source;
	private Node target;
	private Node newSource;
	private Node newTarget;
	
	public Arc getConnection() {
		return connection;
	}
	
	public void setConnection(Arc connection) {
		this.connection = connection;
		this.source = this.newSource = connection.getSource();
		this.target = this.newTarget = connection.getTarget();
	}
	
	public void setNewSource(Node newSource) {
		this.newSource = newSource;
	}

	public void setNewTarget(Node newTarget) {
		this.newTarget = newTarget;
	}

	@Override
	public boolean canExecute() {
		if (newSource instanceof Place && newTarget instanceof Transition) {
			return true;
		}
		if (newSource instanceof Transition && newTarget instanceof Place) {
			return true;
		}
		return false;
	}

	@Override
	public void execute() {
		if (connection == null) {
			return;
		}
		connection.setSource(newSource);
		connection.setTarget(newTarget);
		source.getOutgoings().remove(connection);
		target.getIncomings().remove(connection);
		newSource.getOutgoings().add(connection);
		newTarget.getIncomings().add(connection);
	}

	@Override
	public void undo() {
		if (connection == null) {
			return;
		}
		connection.setSource(source);
		connection.setTarget(target);
		source.getOutgoings().add(connection);
		target.getIncomings().add(connection);
		newSource.getOutgoings().remove(connection);
		newTarget.getIncomings().remove(connection);
	}

	@Override
	public void redo() {
		execute();
	}
}
